package nio;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//tcp服务端(用线程池虽然也可以起到代码可以往下执行的情况，但是这只是伪异步，并未解决阻塞问题)
class TcpServer{

    public static void main(String[] args) throws IOException {
        System.out.println("tcp服务端启动....");
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(8080);
        try{
            while(true){
                final Socket accept = serverSocket.accept();
                cachedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            InputStream inputStream = accept.getInputStream();
                            //转换成String类型
                            byte[] buf = new byte[1024];
                            int len = inputStream.read(buf);
                            String str = new String(buf,0,len);
                            System.out.println("接受内容..." + str);
                        } catch (IOException e) {

                        }
                    }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            serverSocket.close();
        }
    }
}



//tcp客户端
public class TcpClient {

    public static void main(String[] args) throws IOException {
        System.out.println("socket tcp 客户端启动...");
        Socket socket = new Socket("127.0.0.1",8080);
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("李博飞".getBytes());
        socket.close();
    }
}
